package com.qf.sl.youshare.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.qf.sl.youshare.model.ProductCollect;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by IDEA
 * User : sl
 * on 2015/2/26.
 * 19:44
 */
public class DataManager {

    private static DataManager ourInstance;

    private Context context;

    private DBHelper dbHelper;

    private SQLiteDatabase database;

    public static DataManager createInstance(Context context){
        if (ourInstance == null) {
            ourInstance = new DataManager(context);
        }
        return ourInstance;
    }

    public static DataManager getInstance() {
        return ourInstance;
    }

    private DataManager(Context ct) {
        context = ct;
    }

    /**
     * 打开数据库的方法
     * @return 打开的数据库
     */
    private SQLiteDatabase openDatabase(){
        if (database == null) {//如果数据库没有打开
            if (dbHelper == null) {//如果 dbHelper 没有初始化
                dbHelper = new DBHelper(context);//先初始化 DBHelper
            }
            database = dbHelper.getWritableDatabase();//再打开数据库
        }
        return database;
    }

    /**
     * 查询商品收藏表的记录
     * @param userId
     * @return
     */
    public Cursor queryProductFavorite(String userId){
        SQLiteDatabase db = openDatabase();
        Cursor cursor = db.query(
                DBHelper.TABLE_PRODUCT_FAVORITES,
                null,
                "user_id = ?",
                new String[]{userId},
                null,
                null,
                null
        );
        return cursor;
    }

    public void deleteProductFavorite(String userId, String pid){
        SQLiteDatabase db = openDatabase();
        int delete = db.delete(
                DBHelper.TABLE_PRODUCT_FAVORITES,
                "user_id = ? and pid = ?",
                new String[]{userId, pid}
        );

        System.out.println("delete = " + delete);
    }

    public List<ProductCollect> getProductCollect(String userId){
        List<ProductCollect> ret = null;

        SQLiteDatabase db = openDatabase();
        Cursor cursor = db.query(
                DBHelper.TABLE_PRODUCT_FAVORITES,
                null,
                "user_id = ?",
                new String[]{userId},
                null,
                null,
                null
        );

        if (cursor != null) {
            ret = new LinkedList<ProductCollect>();
            while (cursor.moveToNext()){
                ProductCollect productCollect = new ProductCollect();
                productCollect.parseCursor(cursor);

                ret.add(productCollect);
            }
            cursor.close();
        }
        return ret;
    }

    /**
     * 收藏商品
     * @param product 收藏的商品(ProductCollect)
     * @param userId 当前收藏商品的用户,没有用户时，选择默认用户ID = 0000(Constants.DEFAULT_USER_ID)
     * @return 结果 int
     *      <ol>
     *          <li>1 : 新加数据，并且添加成功</li>
     *          <li>2 : 数据库中原本就有该数据，并未继续添加</li>
     *          <li>3 : 数据库尚未打开</li>
     *      </ol>
     */
    public int productCollect(ProductCollect product, String userId){

        SQLiteDatabase db = openDatabase();

        if (db != null) {
            if (product != null) {
                try {
                    List<ProductCollect> productCollects = getProductCollect(userId);
                    if (productCollects != null && productCollects.size() > 0) {
                        boolean isHave = false;
                        for (ProductCollect productCollect : productCollects) {
                            String pid = productCollect.getPid();
                            if (pid.equals(product.getPid())) {
                                isHave = true;
                            }
                        }
                        if (!isHave){
                            db.beginTransaction();
                            ContentValues values = new ContentValues();
                            //按照表的 字段 名，添加数据
                            values.put("pid", product.getPid());
                            values.put("name", product.getName());
                            values.put("price", product.getPrice());
                            values.put("description", product.getDescription());
                            values.put("thumb", product.getThumb());
                            values.put("type", product.getType());
                            values.put("user_id", userId);

                            long rid = db.insert(DBHelper.TABLE_PRODUCT_FAVORITES, null, values);
                            if (rid != -1){
                                db.setTransactionSuccessful();
                                return 1;
                            }
                        }else {
                            db.beginTransaction();
                            db.setTransactionSuccessful();
                            return 2;
                        }
                    }else {
                        db.beginTransaction();
                        ContentValues values = new ContentValues();
                        //按照表的 字段 名，添加数据
                        values.put("pid", product.getPid());
                        values.put("name", product.getName());
                        values.put("price", product.getPrice());
                        values.put("description", product.getDescription());
                        values.put("thumb", product.getThumb());
                        values.put("type", product.getType());
                        values.put("user_id", userId);

                        long rid = db.insert(DBHelper.TABLE_PRODUCT_FAVORITES, null, values);
                        if (rid != -1){
                            db.setTransactionSuccessful();
                            return 1;
                        }
                    }

                }catch (Exception e){
                    e.printStackTrace();
                } finally {
                    db.endTransaction();
                }
            }
        }
        return 3;
    }
}
